<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
        <!-- 提示区 -->
        <el-alert
            title="添加商品信息"
            type="info"
            center
            show-icon
            :closable="false">
        </el-alert>
        <!-- 步骤条  -0转换为数值类型 -->
        <el-steps :space="200" :active="activeIndex-0" finish-status="success"
        align-center>
            <el-step title="基本信息"></el-step>
            <el-step title="商品参数"></el-step>
            <el-step title="商品属性"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="商品内容"></el-step>
            <el-step title="完成"></el-step>
        </el-steps>
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" 
        label-width="100px" label-position="top">
            <el-tabs tab-position="left"
            v-model="activeIndex"
            :before-leave="beforeTabLeave"
            @tab-click="tabClick()">
            <!-- before-leave 切换标签之前的钩子，若返回 false 或者返回 Promise 且被 reject，则阻止切换 -->
            <el-tab-pane label="基本信息" name="0">
                <el-form-item label="商品名称" prop="goods_name">
                    <el-input v-model="addForm.goods_name"></el-input>
                </el-form-item>
                <el-form-item label="商品价格" prop="goods_price">
                    <el-input v-model="addForm.goods_price" type="number"></el-input>
                </el-form-item>
                <el-form-item label="商品重量" prop="goods_weight">
                    <el-input v-model="addForm.goods_weight" type="number"></el-input>
                </el-form-item>
                <el-form-item label="商品数量" prop="goods_number">
                    <el-input v-model="addForm.goods_number" type="number"></el-input>
                </el-form-item>
                <el-form-item label="商品分类" prop="goods_cat">
                    <el-cascader
                    v-model="addForm.goods_cat"
                    :options="cateList"
                    :props="{ expandTrigger: 'hover',
                                label: 'cat_name',
                                value: 'cat_id',
                                children: 'children'  }"
                    @change="handleChange">
                    
                    </el-cascader>
                </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品参数" name="1">
                <el-form-item v-for="i in manyTableData" :key="i.attr_id" :label="i.attr_name">
                    <el-checkbox-group v-model="i.attr_vals">
                        <el-checkbox v-for="(cb,index) in i.attr_vals" :key="index"
                        :label="cb" border></el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品属性" name="2">
                <el-form-item v-for="i in onlyTableData" :key="i.attr_id" :label="i.attr_name">
                    <el-input v-model="i.attr_vals"></el-input>
                </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品图片" name="3">
                <!-- action 图片上传的目标地址 -->
                <!-- 没有使用axios，需自己设置请求头 -->
                <el-upload
                action="http://127.0.0.1:8888/api/private/v1/upload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                list-type="picture"
                :headers="upHeaders">
                <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
            </el-tab-pane>
            <el-tab-pane label="商品内容" name="4">
                <!-- bidirectional data binding（双向数据绑定） -->
                <quill-editor v-model="addForm.goods_introduce"
                ref="myQuillEditor">
                </quill-editor>
                <el-button type="primary" style="margin-top: 10px;"
                @click="add">添加商品</el-button>
            </el-tab-pane>
            </el-tabs>
        </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog
    title="图片预览"
    :visible.sync="previewVisible"
    width="50%">
        <img :src="previewUrl" alt="" style="width: 100%;">
    </el-dialog>
  </div>
</template>

<script>
export default {
    name:'AddPage',
    data(){
        return{
            activeIndex: '0',
            // 商品分类列表
            cateList: [],
            addForm: {
                goods_name: '',
                goods_price: 0,
                goods_weight: 0,
                goods_number: 0,
                // 商品所属数组
                goods_cat: [],
                // 上传图片临时路径
                pics: [],
                // 商品详情描述
                goods_introduce: '',
                // 动态参数与静态参数
                attrs: []
            },
            addFormRules: {
                goods_name: [
                { required: true, message: '请输入商品名称', trigger: 'blur' },
                ],
                goods_price: [
                { required: true, message: '请输入商品价格', trigger: 'blur' },
                ],
                goods_weight: [
                { required: true, message: '请输入商品重量', trigger: 'blur' },
                ],
                goods_number: [
                { required: true, message: '请输入商品数量', trigger: 'blur' },
                ],
                goods_cat: [
                { required: true, message: '请选择商品分类', trigger: 'blur' },
                ],
            },
            // 动态数据
            manyTableData: [],
            onlyTableData: [],
            // 图片上传请求头
            upHeaders: {
                Authorization: window.sessionStorage.getItem('token')
            },
            // 预览图片路径
            previewUrl: '',
            previewVisible: false
        }
    },
    created(){
        this.getCateList()
    },
    methods: {
        async getCateList(){
            const {data:res} = await this.$http.get(`categories`)
            if(res.meta.status !== 200){
                return this.$message.error('获取商品分类失败')
            }
            this.cateList = res.data
            console.log(this.cateList)
        },
        // 级联选择器改变事件
        handleChange(){
            console.log(this.addForm.goods_cat)
            // 只能选择三级菜单
            if(this.addForm.goods_cat.length !== 3){
                this.addForm.goods_cat = []
                this.$message.warning('只能选择三级菜单')
            }
        },
        beforeTabLeave(activeName,oldActiveName){
            // console.log('即将进入act'+activeName,'即将离开oldact'+oldActiveName)
            // return false
            if(oldActiveName == 0 && this.addForm.goods_cat.length !== 3 
            || this.addForm.goods_name === ''){
                this.$message.error('内容不能为空')
                return false
            }
        },
        async tabClick(){
            // console.log(this.activeIndex);
            // 动态参数面板
            if(this.activeIndex === '1'){
                const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes`,{params:{
                    sel: 'many'
                }})
                if(res.meta.status !== 200) return this.$message.error('获取数据失败')
                // console.log(res.data)
                res.data.forEach(item => {
                    // 以' '分割字符串为数组
                    item.attr_vals = item.attr_vals.length===0?[]:item.attr_vals.split(' ')
                });
                this.manyTableData = res.data
            }
            else if(this.activeIndex === '2'){
                const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes`,{params:{
                    sel: 'only'
                }})
                if(res.meta.status !== 200) return this.$message.error('获取数据失败')
                console.log(res.data)
                this.onlyTableData = res.data
            }
        },
        // 预览上传的缩略图
        handlePreview(file){
            // console.log('file',file)
            this.previewUrl = file.response.data.url
            this.previewVisible = true
        },
        // 移除所上传图片事件
        handleRemove(file){
            // console.log('file',file)
            // file得到图片信息
            const filePath = file.response.data.tmp_path
            // 在pics中找到图片对应索引
            const index = this.addForm.pics.findIndex(i=>{
                i.pic === filePath
            })
            // 使用splice删除图片
            this.addForm.pics.splice(index,1)
            // console.log(this.addForm)
        },
        // 图片上传成功
        handleSuccess(respose){
            // 得到图片信息
            const picInfo = {pic: respose.data.tmp_path}
            // 将图片信息push到pics数组中
            this.addForm.pics.push(picInfo)
            console.log(this.addForm)
        },
        // 最后添加商品
        add(){
            this.$refs.addFormRef.validate(async valid=>{
                if(!valid){
                    return this.$message.error('请填写所有必填项')
                }
                // 处理动态参数
                console.log(this.addForm)
                this.manyTableData.forEach(i=>{
                    const newInfo = {
                        attr_id: i.attr_id,
                        attr_vals: i.attr_vals.join(',')
                    }
                    this.addForm.attrs.push(newInfo)
                    console.log(newInfo)
                })
                // 处理静态参数
                this.onlyTableData.forEach(item=>{
                    const newInfo = {
                        attr_id: item.attr_id,
                        attr_vals: item.attr_vals
                    }
                    this.addForm.attrs.push(newInfo)
                })
                // if(this.addForm.attrs.length === 0) return this.$message.warning('请检查商品参数')
                // 重新转回字符串(级联选择器需要数组)需使用深拷贝
                const form = JSON.parse(JSON.stringify(this.addForm))
                form.goods_cat = form.goods_cat.join(',')
                console.log(form)
                const {data:res} = await this.$http.post(`goods`,form)
                if(res.meta.status !== 201){
                    return this.$message.error('必填输入不能为空或0')
                }
                this.$message.success('添加成功')
                this.$router.push('/goods')
            })
        }
    },
    computed: {
        cateId(){
            if(this.addForm.goods_cat.length === 3){
                return this.addForm.goods_cat[2]
            }
            return null
        }
    }
}
</script>

<style lang="less" scoped>
.el-checkbox{
    margin: 0 10px 0 0 !important;
}
</style>